package com.lxyk.dao.user;

import com.lxyk.domain.SysUser;
import org.apache.ibatis.annotations.*;
import org.springframework.security.core.userdetails.User;

import java.util.List;

public interface UserDao {
    //根据用户名查询用户信息(包括角色列表)
    @Select("select * from sys_user where username=#{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roles", column = "id", javaType = List.class,
                many = @Many(select = "com.lxyk.dao.user.RoleDao.findByUid"))
    })
    public SysUser findByName(String username);

    //添加用户
    @Insert("insert into sys_user (username, password,status) values (#{username}, #{password},1)")
    @SelectKey(keyColumn = "id",keyProperty = "id",resultType = Integer.class,
            before = false,statement = {"select last_insert_id()"})
    public void save(SysUser user);

    //查询所有用户
    @Select("select * from sys_user where status=1")
    public List<SysUser> findAll();

    //根据用户id查询所对应的所有角色id
    @Select("SELECT r.id FROM sys_role r, sys_user_role ur " +
            "WHERE ur.rid=r.id AND ur.uid=#{uid}")
    public List<Integer> findRolesByUid(Integer id);

    //删除用户  假删除
    @Update("update sys_user set status=0 where id=#{id}")
    public Integer delete(Integer id);

    //根据id查询
    @Select("select * from sys_user where id=#{id}")
    public SysUser findById(Integer id);

    /**---------------------------中间表--------------------------------------*/

    //根据用户id删除用户角色表信息(中间表)
    @Delete("delete from sys_user_role where uid=#{userId}")
    public void removeRoles(Integer userId);

    //根据角色id删除用户角色表信息(中间表)
    @Delete("delete from sys_user_role where rid=#{roleId}")
    public void removeUsers(Integer roleId);

    //向用户角色表(中间表)插入数据
    @Insert("insert into sys_user_role values (#{uid}, #{rid})")
    public void addRoles(@Param("uid") Integer userId, @Param("rid") Integer rid);



    //更新数据
    @Update("update sys_user set username=#{username},password=#{password} where id=#{id}")
    public Integer update(SysUser user);

    //修改密码
    @Update("update sys_user set password=#{password} where username=#{username}")
    void editPassword(SysUser user);
}
